package cn.duli.xianer.controller;

import cn.duli.xianer.exception.UnauthorizedException;
import cn.duli.xianer.pojo.MyResult;
import cn.duli.xianer.pojo.Users;
import cn.duli.xianer.service.UsersService;
import cn.duli.xianer.utils.JWTUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;


@RestController
public class WebController {

    private static final Logger LOGGER = LogManager.getLogger(WebController.class);

    @Autowired
    private UsersService usersService;


    @PostMapping("/login")
    public MyResult login(@RequestParam("username") String username,
                          @RequestParam("password") String password) {
//        Users user = usersService.findByUsername(username);
//        if (user.getuPwd().equals(password)) {
            return new MyResult(200, "Login success", JWTUtil.sign(username, password),null, null, null);
//        } else {
//            throw new UnauthorizedException();
//        }
    }

    @GetMapping("/article")
    public MyResult article() {
        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return new MyResult(200, "You are already logged in", null, null, null, null);
        } else {
            return new MyResult(200, "You are guest", null, null, null, null);
        }
    }

    @GetMapping("/require_auth")
    @RequiresAuthentication
    public MyResult requireAuth() {
        return new MyResult(200, "You are authenticated", null, null, null, null);
    }

    @GetMapping("/require_role")
    @RequiresRoles("admin")
    public MyResult requireRole() {
        return new MyResult(200, "You are visiting require_role", null, null, null, null);
    }

    @GetMapping("/require_permission")
    @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})
    public MyResult requirePermission() {
        return new MyResult(200, "You are visiting permission require edit,view", null, null, null, null);
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public MyResult unauthorized() {
        return new MyResult(401, "Unauthorized", null, null, null, null);
    }
}
